/**
 * 项目名：admin
 * 包名：com.xuebang.admin.service
 * 文件名：ArticleService.java
 * 版本信息：@version 1.0
 * 日期：2014-1-17-上午11:19:42
 */
package com.xuebang.admin.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xuebang.admin.dao.Finder;
import com.xuebang.admin.dao.Finder.Query;
import com.xuebang.admin.dao.Pagination;
import com.xuebang.admin.entity.NewsContents;
import com.xuebang.admin.entity.NewsTitle;
import com.xuebang.admin.entity.Operator;
import com.xuebang.admin.entity.OperatorGroups;
import com.xuebang.admin.mapper.ContentMapper;
import com.xuebang.admin.mapper.TitleMapper;

/**
 * 项目名称：admin 类名称：ArticleService 类描述： 创建人：xuyang 创建时间：2014-1-17 上午11:19:42
 * 修改人：xuyang 修改时间：2014-1-17 上午11:19:42 修改备注：
 * 
 * @version
 */
@Service
public class ArticleService {

	@Inject
	Finder finder;

	@Inject
	TitleMapper titleMapper;

	@Inject
	ContentMapper contentMapper;

	/**
	 * 获得所有未放入回收站的新闻
	 * 
	 * @param intNewsLimit
	 *            限定条数
	 */
	@Transactional(readOnly = true)
	public Pagination<NewsTitle> getNewsInfo(int intNewsLimit) {
		
		Query que = finder.from("news_title").where("red",0);
		// 得到关联栏目
		String strRelatedColumns = this.getRelatedColumns();
		if(!strRelatedColumns.equals("")){
			que.where("cid in (" + strRelatedColumns + ")");
			return que.orderBy("posttime desc,id desc").paginate(NewsTitle.class,1,intNewsLimit);
		}  else {
			return new Pagination<NewsTitle>(1, 1, 1);
		}
	}
	
	/**
	 * 获得放入回收站的新闻
	 * 
	 * @param intNewsLimit
	 *            限定条数
	 */
	@Transactional(readOnly = true)
	public Pagination<NewsTitle> getNewsInfo(int intNewsLimit,int red) {
		
		Query que = finder.from("news_title").where("red",red);
		// 得到关联栏目
		String strRelatedColumns = this.getRelatedColumns();
		if(!strRelatedColumns.equals("")){
			que.where("cid in (" + strRelatedColumns + ")");
			return que.orderBy("posttime desc,id desc").paginate(NewsTitle.class,1,intNewsLimit);
		} else {
			return new Pagination<NewsTitle>(1, 1, 1);
		}
	}

	/**
	 * 搜索新闻
	 */
	@Transactional(readOnly = true)
	public Pagination<NewsTitle> search(String searchText, int intPageNo,
			int intPageLimit) {

		return search(searchText,0,intPageNo,intPageLimit);
	}
	
	/**
	 * 搜索新闻
	 */
	@Transactional(readOnly = true)
	public Pagination<NewsTitle> search(String searchText,int red, int intPageNo,
			int intPageLimit) {

		searchText = "%" + searchText + "%";
		Query que = finder.from("news_title").like("title",searchText);

		// 得到关联栏目
		String strRelatedColumns = this.getRelatedColumns();
		if(!strRelatedColumns.equals("")){
			que.where("cid in (" + strRelatedColumns + ")");
			que = que.where("red",red);
			que.orderBy("posttime desc,id desc");
			return que.paginate(NewsTitle.class, intPageNo, intPageLimit);
		} else {
			return new Pagination<NewsTitle>(1, 1, 1);
		}
		
		
	}

	/**
	 * 获得指定title的新闻
	 * 
	 * @param intId
	 */
	@Transactional(readOnly = true)
	public NewsTitle findNews(Integer intId) {

		return titleMapper.findNews(intId);
	}

	/**
	 * 获得指定title的新闻
	 * 
	 * @param title
	 * @param intCid
	 */
	@Transactional(readOnly = true)
	public Integer findNewsByName(String title, Integer intCid) {

		return titleMapper.findByTitle(title, intCid);
	}

	/**
	 * 获得指定title的新闻
	 * 
	 * @param title
	 */
	@Transactional(readOnly = true)
	public Integer findNewsByName(String title) {

		return titleMapper.findByTitleNoCol(title);
	}

	/**
	 * 增加新闻
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean addNews(NewsTitle newsTitle, List<NewsContents> newsContent) {

		boolean blnResult = true;
		// 增加新闻标题
		titleMapper.addNewsTitle(newsTitle);
		Integer intNewsID = null;
		// 查找新闻id
		if (newsTitle.getCid() == null) {
			intNewsID = findNewsByName(newsTitle.getTitle());
		} else {
			intNewsID = findNewsByName(newsTitle.getTitle(), newsTitle.getCid());
		}
		if (intNewsID == null) {
			blnResult = false;
		} else {
			newsTitle.setId(intNewsID);
			// 增加新闻内容
			insertContent(intNewsID, newsContent);
//			//System.out.println("内容增加成功");
			// 增加关键字
			insertKeyword(newsTitle);
//			//System.out.println("关键字增加成功");
		}

		return blnResult;
	}

	/**
	 * 增加内容
	 */
	@Transactional(readOnly = true)
	public List<NewsContents> findContentByTid(Integer tid) {

		return contentMapper.findContentByTid(tid);
	}

	/**
	 * 修改新闻
	 * 
	 * @param newsTitle
	 * @param newsContent
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateNews(NewsTitle newsTitle,
			List<NewsContents> lstNewsContent) {

		// 找出以前的关键词
		NewsTitle oldNewsTitle = titleMapper.findNews(newsTitle.getId());

		// 修改新闻标题
		titleMapper.updateNewsTitle(newsTitle);

		// 修改新闻内容
		// contentMapper.updateNewsContent(newsContent);
		// TODO
		updateNewsContent(newsTitle.getId(), lstNewsContent);

		// 修改关键字
		updateKeyword(oldNewsTitle.getKeywords(), newsTitle);
	}

	/**
	 * 删除新闻
	 * 
	 * @param newsTitle
	 * @param newsContent
	 */
	@Transactional(rollbackFor = Exception.class)
	public void delArticles(String[] strArticleIds,String basePath) {

		for(String articleID: strArticleIds){
			if(articleID!=null && !"".equals(articleID.trim())){
				NewsTitle newsTitle = titleMapper.findNews(Integer.parseInt(articleID));
				// 删除标题

				deleteFile(newsTitle.getPicurl(),basePath);
				titleMapper.deleteNewsTitle(newsTitle);
				
				// 删除内容
				contentMapper.deleteContent(newsTitle.getId());
				// 删除关键字
				deleteKeyword(newsTitle);
			}
		}
	}
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public void deleteFile(String sPath,String basePath) {
    	
        File file = new File(basePath.substring(0, basePath.length()-7)+sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println(sPath+"图片删除成功");
        }
    }
	/**
	 * 清空回收站
	 * 
	 */
	@Transactional(rollbackFor = Exception.class)
	public void clearUp(){
		
		// 找到所有的red=1的文章
		List<NewsTitle> lstNewsTitle = titleMapper.findAllDeletedNews();
		for(NewsTitle newsTitle: lstNewsTitle){
			if(newsTitle!=null){
				// 删除标题
				titleMapper.deleteNewsTitle(newsTitle);
				// 删除内容
				contentMapper.deleteContent(newsTitle.getId());
				// 删除关键字
				deleteKeyword(newsTitle);
			}
		}
	}

	/**
	 * 将文章放入回收站
	 * 
	 * @param operatorIds
	 *            文章id
	 */
	@Transactional(rollbackFor = Exception.class)
	public void putIntoRecycleBin(String[] articleIds) {

		for (String strId : articleIds) {
			titleMapper.putIntoRecycleBin(strId);
		}
	}
	
	/**
	 * 还原
	 * 
	 * @param operatorIds
	 *            文章id
	 */
	@Transactional(rollbackFor = Exception.class)
	public void restore(String[] articleIds) {

		for (String strId : articleIds) {
			titleMapper.restore(strId);
		}
	}

	/**
	 * 过滤新闻
	 * 
	 * @param searchText
	 *            搜索项
	 * @param startDate
	 *            开始日期
	 * @param endDate
	 *            截止日期
	 * @param choiceCol
	 *            选中栏目项
	 * @param pageNo
	 *            页码
	 */
	public Pagination<NewsTitle> filterArticles(String searchText, String startDate,
			String endDate, Integer choiceCol, Integer pageNo, Integer pageLimit) {
		return filterArticles(searchText,startDate,endDate,choiceCol,pageNo,pageLimit,0);
	}
	
	/**
	 * 过滤新闻
	 * 
	 * @param searchText
	 *            搜索项
	 * @param startDate
	 *            开始日期
	 * @param endDate
	 *            截止日期
	 * @param choiceCol
	 *            选中栏目项
	 * @param pageNo
	 *            页码
	 */
	public Pagination<NewsTitle> filterArticles(String searchText, String startDate,
			String endDate, Integer choiceCol, Integer pageNo, Integer pageLimit,Integer red) {

		Query que = finder.from("news_title");
		if (searchText != null && !"".equals(searchText.trim())) {
			if (startDate != null && !"".equals(startDate.trim())) {
				// 假如开始时间不为空，则截止时间必定不为空
				if (choiceCol != null && choiceCol.intValue() == -1) {
					// searchText startDate
					que.like("title", '%'+searchText+'%').where("posttime>='" + startDate + "' and posttime<'" + endDate +"'");
				} else if (choiceCol != null && choiceCol.intValue() != -1) {
					// 限制项目
					que.like("title", '%'+searchText+'%')
						.where("posttime>='" + startDate + "' and posttime<'" + endDate +"'")
						.where("cid", choiceCol);
						//.limit(pageNo, pageLimit).all(NewsTitle.class);
				}
			} else {
				// 有截止时间
				if (endDate != null && !"".equals(endDate)) {
					if (choiceCol != null && choiceCol.intValue() == -1) {
						// 各种条件都得满足
						que.like("title", '%'+searchText+'%')
							.where("posttime < '" + endDate + "'");
							//.limit(pageNo, pageLimit).all(NewsTitle.class);
					} else if (choiceCol != null && choiceCol.intValue() != -1) {
						que.like("title", '%'+searchText+'%')
							.where("posttime < '" + endDate + "'").where("cid", choiceCol);
							//.limit(pageNo, pageLimit).all(NewsTitle.class);
					}
				} else {
					// 无截止时间
					if (choiceCol != null && choiceCol.intValue() == -1) {
						// 各种条件都得满足
						que.like("title", '%'+searchText+'%');
						//que.like(" title like '%" + searchText +"%' ");
						//.limit(pageNo, pageLimit).all(NewsTitle.class);
					} else if (choiceCol != null && choiceCol.intValue() != -1) {
						que.like("title", '%'+searchText+'%').where("cid", choiceCol);
							//.limit(pageNo, pageLimit).all(NewsTitle.class);
					}
				}
			}
		} else {
			if (startDate != null && !"".equals(startDate.trim())) {
				if (choiceCol != null && choiceCol.intValue() == -1) {
					que.where("posttime>='" + startDate + "' and posttime<'" + endDate + "'");
					//.limit(pageNo, pageLimit).all(NewsTitle.class);
				} else if (choiceCol != null && choiceCol.intValue() != -1) {
					que.where("posttime>='" + startDate + "' and posttime<'" + endDate +"'")
							.where("cid", choiceCol);
							//.limit(pageNo, pageLimit).all(NewsTitle.class);
				}
			} else {
				// 有截止时间
				if (endDate != null && !"".equals(endDate)) {
					if (choiceCol != null && choiceCol.intValue() == -1) {
						// 各种条件都得满足
						que.where("posttime<='" + endDate + "'");
								//.limit(pageNo, pageLimit).all(NewsTitle.class);
					} else if (choiceCol != null && choiceCol.intValue() != -1) {
						que.where("posttime<='" + endDate + "'").where("cid", choiceCol);
						//.limit(pageNo, pageLimit).all(NewsTitle.class);
					}
				} else {
					// 无截止时间
					if (choiceCol != null && choiceCol.intValue() == -1) {
						//.limit(pageNo, pageLimit).all(NewsTitle.class);
					} else if (choiceCol != null && choiceCol.intValue() != -1) {
						que.where("cid", choiceCol);
						//.limit(pageNo, pageLimit).all(NewsTitle.class);
					}
				}
			}
		}
		// 回收站
		if(red==1){
			que.where("red",1);
		} else {
			que.where("red",0);
		}
		
		// 得到关联栏目
		String strRelatedColumns = this.getRelatedColumns();
		if(!strRelatedColumns.equals("")){
			que.where("cid in (" + strRelatedColumns + ")");
			return que.orderBy("posttime desc,id desc").paginate(NewsTitle.class,pageNo,pageLimit);
		} else {
			return new Pagination<NewsTitle>(1,1,1);
		}

	}
	
	/**
	 * 置顶操作
	 * 
	 * @param Integer 
	 * 			iftop 置顶级别
	 * @param Integer
	 * 			id   新闻ID
	 *  
	 */
	public void makeTop(Integer id,Integer iftop){

		titleMapper.makeTop(id,iftop);
	}
	
	/**
	 * 推荐操作
	 * 
	 * @param Integer 
	 * 			recommend 置顶级别
	 * @param Integer
	 * 			id   新闻ID
	 *  
	 */
	public void recommend(Integer id,Integer recommend){

		titleMapper.recommend(id,recommend);
	}
	
	/**
	 * 查看回收站
	 *
	 * @param Integer
	 * 		  pageNo 页码
	 * @param Integer
	 * 		  intPageLimit 每页限定的条数
	 */
	public Pagination<NewsTitle> viewRecycleBin(Integer pageNo,Integer intPageLimit){
		
		
		Query que = finder.from("news_title").where("red",1);

		// 得到关联栏目
		String strRelatedColumns = this.getRelatedColumns();
		if(!strRelatedColumns.equals("")){
			que.where("cid in (" + strRelatedColumns + ")");
			return que.paginate(NewsTitle.class, pageNo, intPageLimit);
		} else {
			return new Pagination<NewsTitle>(1, 1, 1);
		}
		
	}

	/**
	 * 关键字处理
	 * 
	 * @param NewsTitle
	 *            tempNews 新闻TITLE
	 * @param Keywordid
	 *            keywordid 关键字，文章中间对象
	 * @return
	 */
	private void insertKeyword(NewsTitle newsTitle) {/*

		// 关键字
		if (newsTitle == null || newsTitle.getKeywords() == null) {
			return;
		}
		String[] arrayKeywords = newsTitle.getKeywords().trim().split(",");
		for (String strKeywords : arrayKeywords) {
			if (strKeywords != null && !"".equals(strKeywords.trim())) {
				Keyword resultKeyword = keywordMapper
						.findKeywordByName(strKeywords);
				Keywordid keywordid = new Keywordid();

				// 没有则添加，有则更新
				if (resultKeyword == null) {
					resultKeyword = new Keyword();
					resultKeyword.setIfhide(1);
					resultKeyword.setKeywords(strKeywords);
					resultKeyword.setNum(1);
					// 添加
					keywordMapper.saveKeyword(resultKeyword);
					Keyword tmpKeyword = keywordMapper
							.findKeywordByName(strKeywords);

					// keywordid
					keywordid.setCid(newsTitle.getCid());
					keywordid.setTid(newsTitle.getId());
					keywordid.setKid(tmpKeyword.getId());
					keywordid.setKname(strKeywords);
					keywordidMapper.saveKeywordid(keywordid);
				} else {
					// 更新
					if (resultKeyword.getNum() != null) {
						resultKeyword
								.setNum(resultKeyword.getNum().intValue() + 1);
					} else {
						resultKeyword.setNum(1);
					}
					keywordMapper.updateKeywordNum(resultKeyword.getId(),
							resultKeyword.getNum());

					// keywordid
					keywordid.setCid(newsTitle.getCid());
					keywordid.setTid(newsTitle.getId());
					keywordid.setKid(resultKeyword.getId());
					keywordid.setKname(strKeywords);
					keywordidMapper.saveKeywordid(keywordid);
				}
			}
		}
	*/}

	/**
	 * 关键字处理
	 * 
	 * @param String
	 *            oldKeyWord 更新之前的关键字
	 * @param NewsTitle
	 *            tempNews 新闻TITLE
	 */
	private void updateKeyword(String oldKeyWord, NewsTitle tempNews) {

		// 关键字
		if (tempNews.getKeywords() != null) {
			String[] arrayKeywords = tempNews.getKeywords().trim().split(",");
			String strUpdateKeywords = "";
			for (String strKeywords : arrayKeywords) {
//				//System.out.println("strKeywords:" + strKeywords);
				if ((strKeywords != null && !"".equals(strKeywords.trim()))
						&& (oldKeyWord == null || (oldKeyWord != null && !(","
								+ oldKeyWord + ",").contains("," + strKeywords
								+ ",")))) {
					strUpdateKeywords = strUpdateKeywords + "," + strKeywords;
				}
			}

//			//System.out.println("strUpdateKeywords:" + strUpdateKeywords);
			if (!"".equals(strUpdateKeywords)) {
				NewsTitle newerTitle = new NewsTitle();
				// 没有则添加，有则更新
				BeanUtils.copyProperties(tempNews, newerTitle);
				newerTitle.setKeywords(strUpdateKeywords);
				insertKeyword(newerTitle);
			}
		}

		if (oldKeyWord != null) {
			String[] arrayKeywords = oldKeyWord.trim().split(",");
//			//System.out.println("oldkeywod:" + oldKeyWord);
//			System.out
//					.println("tempNews.getKeywords:" + tempNews.getKeywords());
			for (String strKeywords : arrayKeywords) {/*
				//System.out.println("strKeywords:" + strKeywords);
				if ((strKeywords != null && !"".equals(strKeywords.trim()))
						&& (tempNews.getKeywords() == null || (tempNews
								.getKeywords() != null && !(","
								+ tempNews.getKeywords() + ",").contains(","
								+ strKeywords + ",")))) {
					Keyword keyword = keywordMapper.findKeywordByName(strKeywords);
					// 没有则删除，有则更新
					if (keyword != null && keyword.getNum() != null) {
						if (keyword.getNum() > 1) {
							keyword.setNum(keyword.getNum().intValue() - 1);
							keywordMapper.updateKeywordNum(keyword.getId(),
									keyword.getNum());
						} else {
							keywordMapper.deleteKeyword(keyword.getId());
						}
						keywordidMapper.deleteKeywordid(tempNews.getId(),
								strKeywords);
					}
				}
			*/}
		}
	}

	/**
	 * 关键字处理(包括keyword和keywodid)
	 * 
	 * @param NewsTitle
	 *            tempNews 新闻TITLE
	 */
	private void deleteKeyword(NewsTitle tempNews) {

		// 关键字
		if (tempNews.getKeywords() != null) {
			String[] arrayKeywords = tempNews.getKeywords().trim().split(",");
			for (String strKeywords : arrayKeywords) {
				if (strKeywords != null && !"".equals(strKeywords.trim())) {/*
					Keyword keyword = keywordMapper
							.findKeywordByName(strKeywords);
					//System.out.println("keyword:" + keyword.getKeywords());
					if (keyword != null && keyword.getNum() != null) {
						if (keyword.getNum() > 1) {
							keyword.setNum(keyword.getNum().intValue() - 1);
							keywordMapper.updateKeywordNum(keyword.getId(),
									keyword.getNum());
						} else {
							keywordMapper.deleteKeyword(keyword.getId());
						}
						keywordidMapper.deleteKeywordid(tempNews.getId(),
								strKeywords);
					}
				*/}
			}
		}
	}

	/**
	 * 增加内容
	 * 
	 * @param intTid
	 * @param lstContents
	 */
	private void insertContent(Integer intTid, List<NewsContents> lstContents) {

		for (NewsContents newsContents : lstContents) {
			newsContents.setTid(intTid);
			contentMapper.addNewsContent(newsContents);
		}
	}

	/**
	 * 修改
	 * 
	 * @param lstContents
	 */
	private void updateNewsContent(Integer intTid,
			List<NewsContents> lstContents) {

		List<NewsContents> lstOldContents = contentMapper
				.findContentByTid(intTid);
		if (lstContents == null || lstContents.size() == 0) {
			return;
		}
		if (lstOldContents == null
				|| lstOldContents.size() < lstContents.size()) {
			// 理论上应该有内容
			if (lstOldContents == null) {
				// 将内容增加进去
				insertContent(intTid, lstContents);
			} else {
				int intContentIndex = 0;
				List<NewsContents> lstAddContents = new ArrayList<NewsContents>();
				// 替换旧内容，增加新内容
				for (NewsContents newsContentsItem : lstContents) {
					if (intContentIndex < lstOldContents.size()) {
						newsContentsItem.setId(lstOldContents.get(
								intContentIndex).getId());
						newsContentsItem.setTid(intTid);
						contentMapper.updateNewsContent(newsContentsItem);
					} else {
						lstAddContents.add(newsContentsItem);
					}
					intContentIndex++;
				}
				if (lstAddContents.size() > 0) {
					insertContent(intTid, lstAddContents);
				}
			}
		} else if (lstOldContents.size() == lstContents.size()) {
			int intContentIndex = 0;
			// 替换内容
			for (NewsContents newsContentsItem : lstContents) {
				newsContentsItem.setId(lstOldContents.get(intContentIndex++)
						.getId());
				newsContentsItem.setTid(intTid);
				contentMapper.updateNewsContent(newsContentsItem);
			}
		} else {
			int intContentIndex = 0;
			// 替换旧内容，删除多余内容
			for (NewsContents newsContentsItem : lstOldContents) {
				if (intContentIndex < lstContents.size()) {
					// 更新内容
					newsContentsItem.setContents(lstContents.get(intContentIndex).getContents());
					contentMapper.updateNewsContent(newsContentsItem);
				} else {
					contentMapper.deleteById(lstOldContents
							.get(intContentIndex).getId());
					//System.out.println("删除的是id："
//							+ lstOldContents.get(intContentIndex).getId());
				}
				intContentIndex++;
			}
		}
	}
	
	/**
	 * 得到关联栏目
	 */
	private String getRelatedColumns(){
		
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = attrs.getRequest();
		Operator operator = (Operator)request.getSession().getAttribute("currentOperator");
		if(operator!=null){
			OperatorGroups operatorGroups = operator.getOperatorGroups();
			// 所属角色
			if(operatorGroups!=null){
				String strRelatedColumns = operatorGroups.getRelatedColumns();
				//就是，
				if(strRelatedColumns!=null&&!"".equals(strRelatedColumns.trim())){
					// 去掉空字符串
					strRelatedColumns = strRelatedColumns.trim();
					// 去掉前面的,
					if(strRelatedColumns.length()>0) {
						char charFst = strRelatedColumns.charAt(0);
						if(charFst==','){
							strRelatedColumns = strRelatedColumns.substring(1, strRelatedColumns.length()).trim();
						}
						// 去掉后面的,
						if(strRelatedColumns.length()>0){
							char charLast = strRelatedColumns.charAt(strRelatedColumns.length()-1);
							if(charLast==','){
								strRelatedColumns = strRelatedColumns.substring(0, strRelatedColumns.length()-1).trim();
							}
							if(strRelatedColumns.length()>0){
								return strRelatedColumns;
							} else {
								return "";
							}
						} else {
							return "";
						}
					} else {
						return "";
					}
				} else {
					return "";
				}
			} else {
				return "";
			}
		} else {
			return "";
		}
	}

	public static void main(String[] args) {
		ArticleService ar = new ArticleService();
		ar.filterArticles("", "", "", -1, 2, 10);
		//System.out.println();
	}
}
